package com.saris.primego.service.impl;

import com.saris.primego.common.exception.FileUploadException;
import com.saris.primego.common.properties.CommonProperties;
import com.saris.primego.common.utils.LSkyProUtil;
import com.saris.primego.pojo.vo.UploadFileVO;
import com.saris.primego.service.CommonService;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.UUID;

@Service
public class CommonServiceImpl implements CommonService {
    final Environment env;
    final CommonProperties commonProperties;
    final
    LSkyProUtil lSkyProUtil;

    public CommonServiceImpl(Environment env, CommonProperties commonProperties, LSkyProUtil lSkyProUtil) {
        this.env = env;
        this.commonProperties = commonProperties;
        this.lSkyProUtil = lSkyProUtil;
    }

    /**
     * 上传图片文件至网站本地
     * @param file 图片文件
     * @return 访问Url
     */
    @Override
    public UploadFileVO uploadToLocal(MultipartFile file) {
        try {
            // 校验文件是否为空
            if (file.isEmpty()) {
                throw new FileUploadException("File is empty");
            }

            // 校验文件类型
            String contentType = file.getContentType();
            if (!(contentType != null && contentType.startsWith("image/"))) {
                throw new FileUploadException("File is not an image");
            }

            // 获取原始文件名并清理路径
            String originalFilename = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
            if (originalFilename.contains("..")) {
                throw new FileUploadException("文件名包含非法路径序列");
            }

            // 创建上传目录（如果不存在）
            Path uploadPath = Paths.get(commonProperties.getFileUploadPath());
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成唯一文件名
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID() + fileExtension;

            // 保存文件
            Path targetLocation = uploadPath.resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation);

            // 获取上下文路径（默认是 "/"）
            String contextPath = env.getProperty("server.servlet.context-path", "/");
            // 获取服务器端口
            String port = env.getProperty("local.server.port", "8080");
            // 构建基础URL
            String baseUrl = String.format("http://localhost:%s%s", port, contextPath);

            // 生成访问URL
            String fileDownloadUri = baseUrl + "uploads/" + fileName;
            UploadFileVO uploadFileVO = new UploadFileVO();
            uploadFileVO.setFileDownloadUri(fileDownloadUri);
            uploadFileVO.setTargetLocation(targetLocation.toString());
            return uploadFileVO;
        } catch (IOException e) {
            throw new FileUploadException("文件上传失败：" + e.getMessage());
        } catch (Exception e) {
            throw new FileUploadException("系统错误：" + e.getMessage());
        }
    }

    /**
     * 上传图片至Nas-lsky图床
     * @param file 图片文件
     * @return UploadFileVO
     */
    @Override
    public UploadFileVO uploadToRemote(MultipartFile file) {
        String s = lSkyProUtil.uploadImage(file);
        UploadFileVO uploadFileVO = new UploadFileVO();
        uploadFileVO.setFileDownloadUri(s);
        return uploadFileVO;
    }
}
